/*
 * Copyright 2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.mycompany.controller.account;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.broadleafcommerce.common.exception.ServiceException;
import org.broadleafcommerce.core.web.controller.account.BroadleafLoginController;
import org.broadleafcommerce.core.web.controller.account.ResetPasswordForm;
import org.broadleafcommerce.profile.core.domain.Customer;
import org.broadleafcommerce.profile.web.core.form.RegisterCustomerForm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;



/**
 * The controller responsible for all actions involving logging a customer in
 */
@Controller
public class LoginController extends BroadleafLoginController {
	
	/*private boolean flag=true;

    @Resource(name="blAuthenticationManager")
    private AuthenticationManager authenticationManager;
    
    @Resource(name="blUserDetailsService")
    private UserDetailsService userDetailsService;
	private EncryptionModuleImpl encryption;*/
	//private RegisterCustomerForm registerCustomerForm;
	//Customer customer=null;
	/*@Autowired
	
public void setEncryption(EncryptionModuleImpl encryption) {
		this.encryption = encryption;
	}

	@RequestMapping(value = "/login_demo", method = RequestMethod.POST)
	public String loginValidation(
			HttpServletRequest request,
			HttpServletResponse response,
			Model model,
			@ModelAttribute("loginForm") RegisterCustomerForm loginForm,
			BindingResult errors) {
		System.out.println("LoginController.loginValidation()");
		//String userName = registerCustomerForm.getCustomer().getEmailAddress();
		//System.out.println(userName);

		String passWord = request.getParameter("j_password");
		String userName=request.getParameter("j_username");
		System.out.println(userName);
		System.out.println(passWord);
		String encryptedPassword = encryption.encrypt(passWord);
		System.out.println(encryptedPassword);
		Authentication auth=loginCustomer(userName,encryptedPassword);
//		String s1="authentication";
		
		if(auth==null || !auth.isAuthenticated())
		{
			System.out.println("NOT  In the isAuthentication method");
			return "redirect:login.html";
		}
		else{
			System.out.println("In the isAuthentication method");
			return "redirect:account.html";
			
		}
	}
		public Authentication loginCustomer(String userName,String encryptedPassword){
		UserDetails principal = userDetailsService.loadUserByUsername(userName);
		System.out.println(principal);
			System.out.println("LoginController.loginCustomer()");
		UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
				principal, encryptedPassword, principal.getAuthorities());
		System.out.println(token);
		
		Authentication authentication = null;
		boolean flag = true; 
		try{
		
		authentication = authenticationManager
				.authenticate(token);
		}catch (Throwable e) {
			System.out.println("LoginController.loginCustomer()");
			flag=false;
		}
		
		if(flag){
			System.out.println(authentication);
			SecurityContextHolder.getContext().setAuthentication(authentication);
			System.out.println(authentication);
			flag=false;
			return authentication;
		}else{
			return null;
		}
		
		}*/
//		if (authentication != null) {
//			return getLoginView();
//		} else {
//			return "redirect: login.html";
//		}

	
	

	@RequestMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response, Model model) {
		System.out.println("hi");
		return super.login(request, response, model);
    }

	@RequestMapping(value="/login/forgotPassword", method=RequestMethod.GET)
	public String forgotPassword(HttpServletRequest request, HttpServletResponse response, Model model) {
		return super.forgotPassword(request, response, model);
	}

	@RequestMapping(value="/login/forgotPassword", method=RequestMethod.POST)
	public String processForgotPassword(@RequestParam("emailAddress") String emailAddress, HttpServletRequest request, Model model) {
		return super.processForgotPassword(emailAddress, request, model);
	}   

	@RequestMapping(value="/login/resetPassword", method=RequestMethod.GET)
	public String resetPassword(HttpServletRequest request, HttpServletResponse response, Model model) {
		return super.resetPassword(request, response, model);
	}   

	@RequestMapping(value="/login/resetPassword", method=RequestMethod.POST)
	public String processResetPassword(@ModelAttribute("resetPasswordForm") ResetPasswordForm resetPasswordForm, HttpServletRequest request, HttpServletResponse response, Model model, BindingResult errors) throws ServiceException {
		return super.processResetPassword(resetPasswordForm, request, response, model, errors);
	}   

	@Override
	public String getResetPasswordUrl(HttpServletRequest request) {     
		String url = request.getScheme() + "://" + request.getServerName() + ":" +request.getServerPort() + getResetPasswordPort(request, request.getScheme() + "/");

		if (request.getContextPath() != null && ! "".equals(request.getContextPath())) {
			url = url + request.getContextPath() + "/login/resetPassword";
		} else {
			url = url + "/login/resetPassword";
		}
		return url;
	}

	

	
}
